/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Musicgroup;

/**
 *
 * @author stamatelopoulos
 */
public class ListMusicGroupForm extends javax.swing.JFrame {

    /**
     * Creates new form ListMusicGroupForm
     */
    EntityManager em;
    int selectedRow;
    Musicgroup musicgroup;
   
    public ListMusicGroupForm() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
        manageButtons();
        DBManager.centerOnScreen(this);
    }

        private void manageButtons() {
        selectedRow = jTable1.getSelectedRow();
        jButton2.setEnabled(selectedRow >= 0);
        jButton3.setEnabled(selectedRow >= 0);

        if (selectedRow >= 0) {
            musicgroup = MusicGroupList.get(jTable1.convertRowIndexToModel(selectedRow));
        }
        }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        MusicGroupQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select m from Musicgroup m");
        MusicGroupList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(MusicGroupQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Πίνακας Συγκροτημάτων");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, MusicGroupList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Επωνυμία");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${formationdate}"));
        columnBinding.setColumnName("Ημερ. Δημιουργίας");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nationality}"));
        columnBinding.setColumnName("Εθνικότητα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fgenreId.name}"));
        columnBinding.setColumnName("Είδος Μουσικής");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setForeground(new java.awt.Color(0, 51, 255));
        jLabel1.setText("Συγκροτήματα:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        jButton1.setText("Εισαγωγή");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit.png"))); // NOI18N
        jButton2.setText("Επεξεργασία");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        jButton3.setText("Διαγραφή");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/stock_exit.png"))); // NOI18N
        jButton4.setText("Έξοδος");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton4)
                .addGap(48, 48, 48))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        Musicgroup mg = new Musicgroup();
        em.persist(mg);
        EditMusicGroupForm emgf = new EditMusicGroupForm(mg, false);
        emgf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        
        emgf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    manageButtons();
                    em.persist(mg);
                    MusicGroupList.add(mg);                   
                    em.getTransaction().commit();

                    int row = MusicGroupList.size() - 1;
                    jTable1.setRowSelectionInterval(row, row);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = MusicGroupQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   MusicGroupList.clear();
                   MusicGroupList.addAll(data);
                   manageButtons();
            }
        }

            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_jButton1ActionPerformed

    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        closeMe(true);
        em.close();
        System.exit(0);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        selectedRow = jTable1.getSelectedRow();
        musicgroup = MusicGroupList.get(jTable1.convertRowIndexToModel(selectedRow));
        
        if (selectedRow>=0){
            int c = JOptionPane.showConfirmDialog(null, "Επιθυμείτε σίγουρα να διαγράψετε το Συγκρότημα " + musicgroup.getName() + "?", "Διαγραφή Συγκροτήματος",JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == 0){ 
               Musicgroup mg = MusicGroupList.get(jTable1.convertRowIndexToModel(selectedRow));
               MusicGroupList.remove(mg);
               em.remove(mg);
               em.getTransaction().commit(); 
               JOptionPane.showMessageDialog(null, "Η Διαγραφή του Συγκροτήματος έγινε με επιτυχία!", "ΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);
            }
            manageButtons();
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν έχετε επιλέξει Συγκρότημα για Διαγραφή.", "ΑΝΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);        
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        selectedRow = jTable1.getSelectedRow();
        mg = MusicGroupList.get(jTable1.convertRowIndexToModel(selectedRow));
        
        EditMusicGroupForm emgf = new EditMusicGroupForm(mg, true);
        emgf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);

        emgf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    em.persist(mg);
                    MusicGroupList.set(selectedRow,mg);
                    em.getTransaction().commit(); 
                    thisFrame.setEnabled(true);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = MusicGroupQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   MusicGroupList.clear();
                   MusicGroupList.addAll(data);
                   manageButtons();
            }
        }  
            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        manageButtons();
    }//GEN-LAST:event_jTable1MouseClicked
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
               
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListMusicGroupForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Musicgroup> MusicGroupList;
    private javax.persistence.Query MusicGroupQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    JFrame thisFrame;
    Musicgroup mg;
}
